package com.czk.netty.zerocopy.practice;

import java.io.FileOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * 网络文件传输
 *
 * @Author:ChenZhangKun
 * @Date: 2021/4/9 10:13
 */
public class TransferFileServer {
    public static void main(String[] args) throws IOException {
        // 创建服务器
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        // 配置非阻塞
        //serverSocketChannel.configureBlocking(false);
        // 监听端口
        serverSocketChannel.bind(new InetSocketAddress(8080));
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        // 创建文件输出流
        FileOutputStream fileOutputStream = new FileOutputStream("d://1.txt");
        // 拿到通道
        FileChannel channel = fileOutputStream.getChannel();
        // 监听端口
        while (true) {
            // 接收数据
            SocketChannel socketChannel = serverSocketChannel.accept();
            //
            int count = 0;
            while (count != -1) {
                // 再次读时为-1,此时会结束
                count = socketChannel.read(buffer);
                // 切换为读状态
                buffer.flip();
                // 读取数据
                channel.write(buffer);
                // 切换为写状态
                buffer.flip();
            }
            // 关闭资源
            buffer.rewind();
            channel.close();
            fileOutputStream.close();

        }
    }
}
